package com.hwadee.property.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hwadee.property.mapper.CommunityMapper;
import com.hwadee.property.pojo.Building;
import com.hwadee.property.pojo.Community;
import com.hwadee.property.pojo.House;
import com.hwadee.property.service.IBuildingService;
import com.hwadee.property.service.ICommunityService;
import com.hwadee.property.service.IHouseService;
import com.hwadee.property.dto.PageResult;
import com.hwadee.property.util.BusinessException;
import com.hwadee.property.util.ErrorCodes;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class CommunityServiceImpl extends ServiceImpl<CommunityMapper, Community> implements ICommunityService {

    @Autowired
    private CommunityMapper communityMapper;

    @Autowired
    private IHouseService houseService;

    @Autowired
    private IBuildingService buildingService;

    @Override
    public List<Community> getByName(String communityName) {
        if (communityName == null || communityName.isEmpty()) {
            throw new BusinessException(ErrorCodes.INVALID_PARAMETER, "小区名称不能为空");
        }
        QueryWrapper<Community> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("community_name", communityName);
        return this.list(queryWrapper);
    }

    @Override
    public PageResult<Community> getPage(int current, int size, String name) {
        // 确保 current 至少为 1
        current = Math.max(current, 1);
        size = Math.max(size, 1);

        // 计算 offset（跳过的记录数）
        int offset = (current - 1) * size;

        // 查询总记录数
        int total = communityMapper.countCommunities(name);

        // 查询当前页数据
        List<Community> records = communityMapper.getCommunities(name, size, offset);

        // 返回封装的分页结果
        return new PageResult<>(total, current, size, records);
    }

    @Override
    @Transactional
    public boolean addCommunity(Community community) {
        if (community == null) {
            throw new BusinessException(ErrorCodes.INVALID_PARAMETER, "小区信息不能为空");
        }
        if (community.getCommunityName() == null || community.getCommunityName().isEmpty()) {
            throw new BusinessException(ErrorCodes.INVALID_PARAMETER, "小区名称不能为空");
        }

        // 检查是否已有相同的小区名称（避免重复）
        Community existingCommunity = this.getByName(community.getCommunityName()).stream().findFirst().orElse(null);
        if (existingCommunity != null) {
            throw new BusinessException(ErrorCodes.ALREADY_EXISTS, "该小区已存在！");
        }

        return this.save(community);
    }

    @Override
    public boolean updateCommunity(Community community) {
        if (community == null || community.getId() == null) {
            throw new BusinessException(ErrorCodes.INVALID_PARAMETER, "小区信息或小区ID不能为空");
        }

        // 检查小区是否存在
        Community existingCommunity = this.getById(community.getId());
        if (existingCommunity == null) {
            throw new BusinessException(ErrorCodes.NOT_FOUND, "小区信息不存在");
        }

        return this.updateById(community);
    }

    @Override
    public boolean deleteCommunity(Long id) {
        if (id == null) {
            throw new BusinessException(ErrorCodes.INVALID_PARAMETER, "小区ID不能为空");
        }

        // 检查小区是否存在
        Community existingCommunity = this.getById(id);
        if (existingCommunity == null) {
            throw new BusinessException(ErrorCodes.NOT_FOUND, "小区信息不存在");
        }

        return this.removeById(id);
    }

    @Override
    public List<Community> listByUserId(Long userId) {
        if (userId == null) {
            throw new BusinessException(ErrorCodes.INVALID_PARAMETER, "业主ID不能为空");
        }
        List<House> houses = houseService.listByOwnerId(userId);
        List<Building> buildingList = new ArrayList<>();
        for (House i : houses){
            buildingList.add(buildingService.getById(i.getBuildingId()));
        }
        List<Community> communityList = new ArrayList<>();
        for (Building i : buildingList){
            communityList.add(getById(i.getCommunityId()));
        }

        return communityList;
    }
}
